"""
库存模型
定义库存和库存记录相关的数据模型
"""
from datetime import datetime
import enum

from app.extensions import db

class InventoryType(enum.Enum):
    """库存操作类型枚举"""
    IN = 'in'  # 入库
    OUT = 'out'  # 出库
    ADJUST = 'adjust'  # 调整(盘点)
    INIT = 'init'  # 初始化
    RESERVE = 'reserve'  # 预留
    RELEASE = 'release'  # 释放

class Inventory(db.Model):
    """库存模型"""
    __tablename__ = 'inventory'
    
    id = db.Column(db.Integer, primary_key=True)
    product_id = db.Column(db.Integer, db.ForeignKey('products.id'), nullable=False)
    variant_id = db.Column(db.Integer, db.ForeignKey('product_variants.id'))
    stock = db.Column(db.Integer, default=0)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    # 关联
    product = db.relationship('Product')
    variant = db.relationship('ProductVariant')
    
    def __repr__(self):
        return f'<Inventory {self.id}>'

class InventoryRecord(db.Model):
    """库存记录模型"""
    __tablename__ = 'inventory_record'
    
    id = db.Column(db.Integer, primary_key=True)
    product_id = db.Column(db.Integer, db.ForeignKey('product.id'), index=True)
    variant_id = db.Column(db.Integer, db.ForeignKey('product_variant.id'), index=True)
    type = db.Column(db.String(20), nullable=False)
    quantity = db.Column(db.Integer, nullable=False)
    balance = db.Column(db.Integer, nullable=False)
    notes = db.Column(db.Text)
    operator_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    
    def __repr__(self):
        return f'<InventoryRecord {self.id}>'
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'product_id': self.product_id,
            'variant_id': self.variant_id,
            'type': self.type,
            'quantity': self.quantity,
            'balance': self.balance,
            'notes': self.notes,
            'operator_id': self.operator_id,
            'created_at': self.created_at.isoformat() if self.created_at else None
        } 